package com.atguigu.tingshu.order.consumer;


import com.atguigu.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 接收订单的支付结果消息后 将订单改为已支付状态
 */
@Component
@Log4j2
public class OrderPaymentMessageConsumer {
    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 接收消息修改订单的支付状态
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = "tingshu_order_queue")
    public void updateOrder(Channel channel, Message message){
        // 获取消息内容
        String result = new String(message.getBody());
        // 获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 修改订单支付状态
            orderInfoService.updateOrder(result);
            // 确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            // 判断是否为重发消息
            if (messageProperties.getRedelivered()){
                // 是 记录日志后拒绝
                log.error("两次修改订单支付状态失败: " + e.getMessage() + ", 消息报文: " + result);
                // 拒绝消息
                channel.basicReject(deliveryTag,false);
            }else {
                // 否 放回队列重新消费
                channel.basicReject(deliveryTag,true);
            }
        }
    }
}
